package com.gongyou.gateway.filter;

import com.gongyou.gateway.entity.FilterProperties;
import com.gongyou.gateway.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @Author LiQuanPing
 * @Date 2021-03-23
 * @Version 1.8
 * @creed: ♂♂Talk is cheap,show me the code♀♀
 * 网关鉴权过滤器
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Autowired
    private FilterProperties filterProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

       System.out.println("经过令牌过滤器");
     // System.out.println("经过令牌过滤器"+filterProperties.getAllowPaths());
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();

      /*  if (path.contains(".css") || path.contains(".js") || path.contains("js") || path.contains("/image") || path.contains("/lib") || path.contains("/fonts") || path.contains("/lib") || path.contains(".html")|| path.contains("report/minData") || path.contains("report/hourData") || path.contains("report/dayData") || path.contains("report/warnData")) {
                return chain.filter(exchange);
        }*/
        //遍历白名单,进行放行
        List<String> list = filterProperties.getAllowPaths();
        for (String s : list) {
            if (path.contains(s)) {
                return chain.filter(exchange);//放行
            }
        }

        //获取请求头信息
        HttpHeaders headers = request.getHeaders();
        //在请求头中获取令牌
        String token = headers.getFirst("token");
        //判断请求头是否有令牌
        if (StringUtils.isEmpty(token)) {
            //token为空证明没有令牌  在响应中设置状态码,返回没有权限访问
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            //如果有令牌就进行解析
            JwtUtil.parseJWT(token);  //此处如果令牌不对 时间过期等等因素  抛出异常信息证明解析不成功
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);//给响应头设置状态码
            return response.setComplete();  //设置完成  返回
        }
        //headers.set("user","zhangsan");
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
